package com.tastesport.chat.util;

import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URI;
import java.net.URISyntaxException;


public class WebsocketClient {

    private static Logger logger = LoggerFactory.getLogger(WebsocketClient.class);

    public static WebSocketClient client;

    public void connection(String msg, String hostIP) {
        try {
            client = new WebSocketClient(new URI(hostIP), new Draft_6455()) {
                @Override
                public void onOpen(ServerHandshake serverHandshake) {
                    logger.info("握手成功");
                }

                @Override
                public void onMessage(String msg) {
                    //logger.info("收到消息=========="+msg);
                    if (msg.equals("youarepagepig")) {
                        client.close();
                    }
                }

                @Override
                public void onClose(int i, String s, boolean b) {
                    logger.info("链接已关闭");
                }

                @Override
                public void onError(Exception e) {
                    e.printStackTrace();
                    logger.info("发生错误已关闭");
                }
            };
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

        client.connect();
        //logger.info(client.getDraft());
        while (!client.getReadyState().equals(WebSocket.READYSTATE.OPEN)) {
            logger.info("");
        }
//        client.send("哈喽,连接一下啊");
        //连接成功,发送信息
        client.send(msg);
        //关闭连接
        client.close();
    }

    /*public static void main(String[] args){
        int i = 0;

//        bb.setGroupId("1");
        BroadcastWsBody bb=null;
        connection(JSON.toJSONString(bb),"ws://43.241.252.72:8888");
        Scanner scan = new Scanner(System.in);
        while(true){
            bb = new BroadcastWsBody(50, "test", 1
                    , scan.nextLine()*//*"eric"+" 抢到了"+"wd"
                    +"的红包"+i+"元！"*//*);
            bb.setFrom("系统消息");
            client.send(JSON.toJSONString(bb));

            System.out.println(JSON.toJSONString(bb));
            i++;
        }
    }*/
}
